package cn.sdormitory.smartdor.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.sdormitory.basedata.dto.StudentLeaveDTO;
import cn.sdormitory.basedata.entity.BDevice;
import cn.sdormitory.basedata.entity.BStudent;
import cn.sdormitory.basedata.service.BStudentService;
import cn.sdormitory.basedata.vo.BStudentLeaveListVo;
import cn.sdormitory.basedata.vo.StudentLeaveVO;
import cn.sdormitory.common.api.CommonResult;
import cn.sdormitory.common.constant.CommonConstant;
import cn.sdormitory.common.utils.SmsSendTemplate;
import cn.sdormitory.smartdor.dao.SdLeaveDao;
import cn.sdormitory.smartdor.entity.SdAttence;
import cn.sdormitory.smartdor.entity.SdDevice;
import cn.sdormitory.smartdor.entity.SdLeave;
import cn.sdormitory.smartdor.service.SdAttenceService;
import cn.sdormitory.smartdor.service.SdLeaveService;
import cn.sdormitory.sysset.entity.SyssetSmsTemplate;
import cn.sdormitory.sysset.service.SyssetSmsTemplateService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @创建人：zhouyang
 * @创建时间：2020/11/27 17:44
 * @version：V1.0
 */
@Slf4j
@Service("sdLeaveService")
public class SdLeaveServiceImpl  extends ServiceImpl<SdLeaveDao, SdLeave> implements SdLeaveService {
    @Resource
    BStudentService bStudentService;

    @Autowired
    SyssetSmsTemplateService syssetSmsTemplateService;

    @Autowired
    SdAttenceService sdAttenceService;

    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public IPage<SdLeave> getPage(Map<String, Object> params) {
        int pageSize = Integer.parseInt(String.valueOf(params.get("pageSize")));
        int pageNum = Integer.parseInt(String.valueOf(params.get("pageNum")));

        String studentNo = (String) params.get("studentNo");
        String leaveType = (String) params.get("leaveType");
        String status = (String) params.get("status");
        String className = (String) params.get("className");
        String studentName = (String) params.get("studentName");
        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");

        LambdaQueryWrapper<SdLeave> wrapper = new LambdaQueryWrapper<>();

        if (StrUtil.isNotEmpty(studentNo)) {
            wrapper.eq(SdLeave::getStudentNo, studentNo);
        }
        if (StrUtil.isNotEmpty(leaveType)) {
            wrapper.eq(SdLeave::getLeaveType, leaveType);
        }
        if (StrUtil.isNotEmpty(status)) {
            wrapper.eq(SdLeave::getStatus, status);
        }
        if (StrUtil.isNotEmpty(className)) {
            wrapper.like(SdLeave::getClassName, className);
        }
        if (StrUtil.isNotEmpty(studentName)) {
            wrapper.like(SdLeave::getStudentName, studentName);
        }
        if (StrUtil.isNotEmpty(startDate)) {
            wrapper.eq(SdLeave::getStartDate, startDate);
        }
        if (StrUtil.isNotEmpty(endDate)) {
            wrapper.eq(SdLeave::getEndDate, endDate);
        }


        wrapper.apply(params.get(CommonConstant.SQL_FILTER) != null, (String) params.get(CommonConstant.SQL_FILTER));
        return page(new Page<>(pageNum, pageSize), wrapper);
    }

    @Override
    public SdLeave getSdLeaveById(Long id) {
        return getById(id);
    }

    @Override
    public int create(SdLeave sdLeave) {
        return this.baseMapper.insert(sdLeave);
    }

    @Override
    public int create1(SdLeave sdLeave,BStudent bStudent) {
        int insert = this.baseMapper.insert(sdLeave);
        if (insert > 0) {
            //向考勤表添加考勤信息
            SdAttence sdAttence = new SdAttence();
            sdAttence.setAccessDate(new Date());
            sdAttence.setStudentNo(bStudent.getStudentNo());
            sdAttence.setAttenceStatus(CommonConstant.ATTENDANCE_LEAVE);
            sdAttence.setBdormitoryId(bStudent.getBdormitoryId());
            sdAttence.setBuildingNo(bStudent.getBuildingNo());
            sdAttence.setStorey(bStudent.getStorey());
            sdAttence.setDormitoryNo(bStudent.getDormitoryNo());
            sdAttence.setCreateTime(new Date());
            sdAttence.setModifyTime(new Date());
//               if(sdLeave.getStartDate().equals(sdLeave.getEndDate())){
//                try {
//                    sdAttence.setAccessDate(sdf.parse(sdLeave.getStartDate()));
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//                insert= sdAttenceService.insert(sdAttence);

//            SyssetSmsTemplate bySmsTypee = syssetSmsTemplateService.getBySmsTypee(CommonConstant.SMS_TEMPLATE_TYPE_LEAVE);
                //发送短信给家长
//            SmsSendTemplate.sms(bStudent.getParentPhone(), bySmsTypee.getSmsContent().replace(CommonConstant.SMS_TEMPLATE_STR, bStudent.getStudentName()));

//            }else{
                //2021-11-1需求变更（支持一次性请假多天）
                try {
                   // List<String> datesRange=new ArrayList<>();
                    Calendar calendar=new GregorianCalendar();
                    calendar.setTime(sdf.parse(sdLeave.getStartDate()));
                    Calendar endCalendar=new GregorianCalendar();
                    endCalendar.setTime(sdf.parse(sdLeave.getEndDate()));
                    // 如果开始、结束日期相同，则while循环次数为0
                    while (calendar.before(endCalendar)){
                        sdAttence.setAccessDate(calendar.getTime());
                        insert= sdAttenceService.insert(sdAttence);
                        calendar.add(Calendar.DATE,1);
                    }
                   // datesRange.add(sdLeave.getEndDate());
                    sdAttence.setAccessDate(sdf.parse(sdLeave.getEndDate()));
                    insert= sdAttenceService.insert(sdAttence);
                  //  System.out.println(datesRange);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            }

        return insert;
    }

    @Override
    public int delete(Long id) {
        return this.baseMapper.deleteById(id);
    }

    @Override
    public int update(Long id, SdLeave sdLeave) {
        sdLeave.setId(id);
        int result= this.baseMapper.updateById(sdLeave);
        int insert=0;
        int deleteCount=0;
        //根据学号+请假日期查询考勤表中对应的所有数据删除再新增考勤表数据
        try {
            SdAttence sdAttence = new SdAttence();
            BStudent bStudent=bStudentService.getByStudentNo(sdLeave.getStudentNo());
            sdAttence.setAccessDate(new Date());
            sdAttence.setStudentNo(sdLeave.getStudentNo());
            sdAttence.setAttenceStatus(CommonConstant.ATTENDANCE_LEAVE);
            sdAttence.setBdormitoryId(bStudent.getBdormitoryId());
            sdAttence.setBuildingNo(bStudent.getBuildingNo());
            sdAttence.setStorey(bStudent.getStorey());
            sdAttence.setDormitoryNo(bStudent.getDormitoryNo());
            sdAttence.setCreateTime(new Date());
            sdAttence.setModifyTime(new Date());
            Calendar calendar=new GregorianCalendar();
            calendar.setTime(sdf.parse(sdLeave.getStartDate()));
            Calendar endCalendar=new GregorianCalendar();
            endCalendar.setTime(sdf.parse(sdLeave.getEndDate()));
            // 如果开始、结束日期相同，则while循环次数为0
            while (calendar.before(endCalendar)){
                sdAttence.setAccessDate(calendar.getTime());
                deleteCount=sdAttenceService.deleteByStuNoAndADate(sdLeave.getStudentNo(),sdf.format(calendar.getTime()));
                insert= sdAttenceService.insert(sdAttence);
                calendar.add(Calendar.DATE,1);
            }
            sdAttence.setAccessDate(sdf.parse(sdLeave.getEndDate()));
            deleteCount=sdAttenceService.deleteByStuNoAndADate(sdLeave.getStudentNo(),sdf.format(calendar.getTime()));
            insert= sdAttenceService.insert(sdAttence);
        } catch (ParseException e) {
            e.printStackTrace();
        }
       return  result;
    }

    @Override
    public int deleteByIds(Long[] ids) {
        int deleteCount=0;
        //根据学号+请假日期查询考勤表中对应的所有数据删除
        for (Long id:ids) {
            SdLeave sdLeave=this.baseMapper.selectById(id);
            Calendar calendar=new GregorianCalendar();
            Calendar endCalendar=new GregorianCalendar();
            try {
                calendar.setTime(sdf.parse(sdLeave.getStartDate()));
                endCalendar.setTime(sdf.parse(sdLeave.getEndDate()));
                // 如果开始、结束日期相同，则while循环次数为0
                while (calendar.before(endCalendar)){
                    deleteCount=sdAttenceService.deleteByStuNoAndADate(sdLeave.getStudentNo(),sdf.format(calendar.getTime()));
                    calendar.add(Calendar.DATE,1);
                }
                deleteCount=sdAttenceService.deleteByStuNoAndADate(sdLeave.getStudentNo(),sdf.format(calendar.getTime()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        int result=this.baseMapper.deleteBatchIds(Arrays.asList(ids));
        return result;
    }

    @Override
    public int updateStatusApprove(Long id, String status) {
        SdLeave sdLeave= new SdLeave();
        sdLeave.setId(id);
        sdLeave.setStatus(status);
        return this.baseMapper.updateById(sdLeave);
    }

    @Override
    public SdLeave getLeaveByStuNoAndLeaDate(String studentNo, String startDate,String endDate) {
//        LambdaQueryWrapper<SdLeave> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(SdLeave::getStudentNo, studentNo);
//        wrapper.eq(SdLeave::getLeaveDate, leaveDate);
//        return this.baseMapper.selectOne(wrapper);
        return this.baseMapper.getLeaveByStuNoAndLeaDate(studentNo,startDate,endDate);
    }

    @Override
    public int insert(SdLeave sdLeave) {
        //判断学号+姓名+班级是否存在
        BStudent bStudent = bStudentService.getByStuNoAndNameAndClassName(sdLeave.getStudentNo(), sdLeave.getStudentName(), sdLeave.getClassName());
        if (bStudent == null) {
            return -2;
        }

        SdLeave sdLeave1 = this.getLeaveByStuNoAndLeaDate(sdLeave.getStudentNo(), sdLeave.getStartDate(), sdLeave.getEndDate());

        if (sdLeave1 == null) {
            sdLeave.setStatus(CommonConstant.PARENT_CONFIRE_PASS);
            sdLeave.setCreateTime(new Date());
            sdLeave.setStudentPhone(bStudent.getPhone());
            sdLeave.setClassId(bStudent.getClassId());
            if ("".equals(sdLeave.getStudentName()) || sdLeave.getStudentName() == null) {
                sdLeave.setStudentName(bStudent.getStudentName());
            }
            if ("".equals(sdLeave.getClassName()) || sdLeave.getClassName() == null) {
                sdLeave.setClassName(bStudent.getClassName());
            }
            int insert = this.baseMapper.insert(sdLeave);
            if (insert > 0) {
                //向考勤表添加考勤信息
                SdAttence sdAttence = new SdAttence();
                sdAttence.setAccessDate(new Date());
                sdAttence.setStudentNo(bStudent.getStudentNo());
                sdAttence.setAttenceStatus(CommonConstant.ATTENDANCE_LEAVE);
                sdAttence.setBdormitoryId(bStudent.getBdormitoryId());
                sdAttence.setBuildingNo(bStudent.getBuildingNo());
                sdAttence.setStorey(bStudent.getStorey());
                sdAttence.setDormitoryNo(bStudent.getDormitoryNo());
                //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

//                try {
//                    sdAttence.setAccessDate(sdf.parse(sdLeave.getStartDate()));
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//                sdAttence.setCreateTime(new Date());
//                sdAttence.setModifyTime(new Date());
//                insert= sdAttenceService.insert(sdAttence);
//                SyssetSmsTemplate bySmsTypee = syssetSmsTemplateService.getBySmsTypee(CommonConstant.SMS_TEMPLATE_TYPE_LEAVE);
                //发送短信给家长
//                SmsSendTemplate.sms(bStudent.getParentPhone(), bySmsTypee.getSmsContent().replace(CommonConstant.SMS_TEMPLATE_STR, bStudent.getStudentName()));
                //2021-11-1需求变更（支持一次性请假多天）
                try {
                   // List<String> datesRange = new ArrayList<>();
                    Calendar calendar = new GregorianCalendar();
                    calendar.setTime(sdf.parse(sdLeave.getStartDate()));
                    Calendar endCalendar = new GregorianCalendar();
                    endCalendar.setTime(sdf.parse(sdLeave.getEndDate()));
                    // 如果开始、结束日期相同，则while循环次数为0
                    while (calendar.before(endCalendar)) {
                        sdAttence.setAccessDate(calendar.getTime());
                        insert = sdAttenceService.insert(sdAttence);
                        calendar.add(Calendar.DATE, 1);
                    }
                    //datesRange.add(sdf.format(sdLeave.getEndDate()));
                    sdAttence.setAccessDate(sdf.parse(sdLeave.getEndDate()));
                    insert = sdAttenceService.insert(sdAttence);
                    //System.out.println(datesRange);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            return insert;
        } else {
            return -1;
        }
    }

    @Override
    public List<SdLeave> getLeaveListByTeaId(String classTeacherId, String className, String studentNo, String leaveType, String status, String studentName,String startDate,String endDate,int pageNum, int pageSize) {
        int currIndex=(pageNum-1)*pageSize;
        return this.baseMapper.getLeaveListByTeaId(classTeacherId,className,studentNo,leaveType,status,studentName,startDate,endDate,currIndex,pageSize);
    }

    @Override
    public int getLeaveListByTeaIdCount(String classTeacherId, String className, String studentNo, String leaveType, String status, String studentName,String startDate,String endDate,int pageNum, int pageSize) {
        int currIndex=(pageNum-1)*pageSize;
        return this.baseMapper.getLeaveListByTeaIdCount(classTeacherId,className,studentNo,leaveType,status,studentName,startDate,endDate,currIndex,pageSize);
    }

    @Override
    public IPage<StudentLeaveVO> getStudentLeaveList(StudentLeaveDTO query) {
        Integer pageNum = query.getPageNum();
        Integer pageSize = query.getPageSize();
        int startNum = (pageNum - 1) * pageSize;
        int count = this.baseMapper.getStudentLeaveCount(query);
        List<StudentLeaveVO> list = this.baseMapper.getStudentLeaveList(startNum,pageSize,query);
        IPage<StudentLeaveVO> page = new Page<>();
        page.setTotal(count);
        page.setRecords(list);
        return page;
    }


}
